<?
    final class FirmwaresController extends PrincipioLab_Controller_Action
    {
        const ACTION_VIEW = 0;
        const ACTION_INDEX = 1;
        const ACTION_EDIT = 2;
        const ACTION_ADD = 3;


        private function setActionViewData($action)
        {
            switch ($action)
            {
                case self::ACTION_INDEX:
                    Principio_Common::setButtons(
                        "Apply",
                        "ajaxFirmwares({id: 0, action: 'index', use_inner: true, no_refresh: true})",
                        "ajaxFirmwares({id: 0, action: 'index', use_inner: true, no_apply: true})"
                    );
                    break;

                case self::ACTION_ADD:
                    Principio_Common::setButtons(
                        "Add firmware",
                        "ajaxFirmwares({id: -1, action: 'add', use_inner: true});",
                        "addItem({menu: 'firmwares', container: 'inner'});"
                    );
                    break;

                case self::ACTION_EDIT:
                    $model_action_menu = new Principio_Model_ActionMenu();
                    $model_action_menu->setJsAjaxFunction("Firmwares")->setItemID($this->view->model_firmware->getID())->
                        setMenu(Principio_Model_MenuItem::fromArray(['Edit' => "edit", 'Delete' => "delete"]));

                    $this->view->model_action_menu = $model_action_menu;

                    Principio_Common::setButtons(
                        "Apply",
                        "ajaxFirmwares({id: ".$this->view->model_firmware->getID().", action: 'edit'});",
                        "ajaxFirmwares({id: ".$this->view->model_firmware->getID().", action: 'edit', no_apply: true});"
                    );
                    break;

            };
        }


        public function indexAction()
        {
            if ($this->is_post)
            {
                $this->view->title = "Firmwares";

                // TODO : take default value from settings
                $this->view->model_option_upgrade_error_retry_delay = Principio_Model_OptionMapper::fetch(Principio_Model_OptionMapper::OPTION_UPGRADE_ERROR_RETRY_DELAY);

                if (($this->is_apply) && ($this->checkPostItemInt("upgrade_error_retry_delay", "Upgrade Error Retry Delay")))
                {
                    $this->view->model_option_upgrade_error_retry_delay->setValue($this->post_data['upgrade_error_retry_delay']);
                    Principio_Model_OptionMapper::save($this->view->model_option_upgrade_error_retry_delay);
                    Principio_Common::reportMessage("Firmwares options were updated.");
                };

                $this->setActionViewData(self::ACTION_INDEX);
            };
        }


        public function viewAction()
        {
            return $this->editAction(self::ACTION_VIEW);
        }


        public function addAction()
	    {
            if ($this->is_post)
            {
                $this->view->title = "Add a new firmware";
                $this->view->action = "add";

                $this->view->is_add = true;
                $this->view->model_firmware = new Principio_Model_Firmware();
                $this->view->used_in_types = array();

                $this->setActionViewData(self::ACTION_ADD);

                if ($this->is_apply)
		        {
                    if ($this->validate())
                    {
                        if (Principio_Model_FirmwareMapper::save($this->view->model_firmware) !== false)
                        {
                            Principio_Common::reportMessage("Firmware was added.");
                            $this->view->is_add = false;
                            $this->view->action = "view";
                            $this->view->title = "View and Edit firmware [".$this->view->model_firmware->getCaption()."]";
                            $this->view->version = $this->calculateVersion($this->view->model_firmware->getFileName());
                            $this->setActionViewData(self::ACTION_EDIT);
                        };
                    };
                };
            };
	    }


        public function editAction($action = self::ACTION_EDIT)
        {
            if (($this->is_post) && ($this->checkPostItemInt("id", "Firmware ID")))
            {
                $this->view->is_add = false;
                $this->view->action = ($action == self::ACTION_EDIT) ? "edit" : "view";
                $this->view->model_firmware = Principio_Model_FirmwareMapper::get($this->post_data['id']);
                $this->view->used_in_types = Principio_Model_TypeMapper::usedFirmware($this->view->model_firmware);
                $model_firmware_old = clone $this->view->model_firmware;

                if (($this->is_apply) && ($this->validate(true)))
                {
                    if (Principio_Model_FirmwareMapper::save($this->view->model_firmware))
                        Principio_Common::reportMessage("Firmware was updated.");
                };

                $this->view->version = $this->calculateVersion($this->view->model_firmware->getFileName());
                $this->view->title = "View and Edit firmware [".(Principio_Common::$is_error ? $model_firmware_old->getCaption() : $this->view->model_firmware->getCaption())."]";

                $this->setActionViewData(self::ACTION_EDIT);
            };
        }


        public function deleteAction()
        {
            if ($this->is_post)
            {
                if ($this->checkPostItemInt("id", "Firmware ID"))
                {
                    if (Principio_Model_FirmwareMapper::delete(Principio_Model_FirmwareMapper::get($this->post_data['id'])))
                        Principio_Common::reportMessage("Firmware was deleted.");
                };
            };
        }


        private function calculateVersion($version)
        {
            $matches = array();
            if (preg_match("/^((spa|pap2t)[0-9]*-)(.*).bin$/", $version, $matches))
                return preg_replace("/([a-zA-Z])+/", "($1)", str_replace("-", ".", $matches[3]));
            else
                return "";
        }



        public function versionAction()
        {
            if ($this->is_post)
            {
                if (isset($this->post_data['version']))
                    $this->view->version = $this->calculateVersion($this->post_data['version']);
            };
        }


        private function validate($is_edit = false)
        {
            if ($this->checkPostItemString("caption", "Caption"))
                $this->view->model_firmware->setCaption($this->post_data['caption']);

            if ($this->checkPostItemString("version", "Version"))
                $this->view->model_firmware->setVersion($this->post_data['version']);

            if (!Principio_Common::$is_error)
            {
                Principio_Common::checkValidity(Principio_Model_FirmwareMapper::checkUniqueCaption($this->view->model_firmware), "Firmware with caption '".$this->view->model_firmware->getCaption()."' already exists.");
                if (!$is_edit)
                {
                    if ($this->checkFileItem("firmware"))
                    {
                        $this->view->model_firmware->setTmpFileName($_FILES['firmware']['tmp_name']);
                        $this->view->model_firmware->setFileName($_FILES['firmware']['name']);
                        Principio_Common::checkValidity(Principio_Model_FirmwareMapper::checkUniqueFileName($this->view->model_firmware), "Firmware with file name '".$this->view->model_firmware->getFileName()."' already exists.");
                    };
                };
            };

            return !Principio_Common::$is_error;
        }
}